/**
 * 
 */
package com.projetIE.prudhomme_duisit.listener;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.projetIE.prudhomme_duisit.GetSituationResponse;
import com.projetIE.prudhomme_duisit.GetSituationResponse.ReponseMeteo;
import com.projetIE.prudhomme_duisit.GetSituationResponse.ReponseMeteo.Meteo;
import com.projetIE.prudhomme_duisit.GetSituationResponse.RequeteMeteo;
import com.projetIE.prudhomme_duisit.PrudhommeDuisitImpl;

/**
 * @author Propriétaire
 * 
 */
public class ReceiveListener implements MessageListener {
	
	/**
	 * 
	 */
	public static Logger	    LOG	= Logger.getLogger(ReceiveListener.class);
	
	private PrudhommeDuisitImpl	associate;
	
	/**
	 * @param a
	 */
	public ReceiveListener(PrudhommeDuisitImpl a) {
		associate = a;
	}
	
	public void onMessage(Message message) {
		try {
			if (message instanceof TextMessage) {
				GetSituationResponse toStore = new GetSituationResponse();
				toStore.setReponseMeteo(new ReponseMeteo());
				toStore.setRequeteMeteo(new RequeteMeteo());
				toStore.getReponseMeteo().setMeteo(new Meteo());
				
				String msgText = ((TextMessage) message).getText();
				Document doc = stringToDom(msgText);
				
				NodeList list = doc.getElementsByTagName("client");
				toStore.getRequeteMeteo().setClient(list.item(0).getTextContent());
				list = doc.getElementsByTagName("pays");
				toStore.getRequeteMeteo().setPays(list.item(0).getTextContent());
				list = doc.getElementsByTagName("ville");
				toStore.getRequeteMeteo().setVille(list.item(0).getTextContent());
				list = doc.getElementsByTagName("lieu");
				toStore.getReponseMeteo().getMeteo().setLieu(list.item(0).getTextContent());
				list = doc.getElementsByTagName("date-heure");
				toStore.getReponseMeteo().getMeteo().setDateHeure(list.item(0).getTextContent());
				list = doc.getElementsByTagName("vent");
				toStore.getReponseMeteo().getMeteo().setVent(list.item(0).getTextContent());
				list = doc.getElementsByTagName("visibilite");
				toStore.getReponseMeteo().getMeteo().setVisibilite(list.item(0).getTextContent());
				list = doc.getElementsByTagName("ciel");
				toStore.getReponseMeteo().getMeteo().setCiel(list.item(0).getTextContent());
				list = doc.getElementsByTagName("temperature");
				toStore.getReponseMeteo().getMeteo().setTemperature(list.item(0).getTextContent());
				list = doc.getElementsByTagName("point-rosee");
				toStore.getReponseMeteo().getMeteo().setPointRosee(list.item(0).getTextContent());
				list = doc.getElementsByTagName("humidite");
				toStore.getReponseMeteo().getMeteo().setHumidite(list.item(0).getTextContent());
				list = doc.getElementsByTagName("pression");
				toStore.getReponseMeteo().getMeteo().setPression(list.item(0).getTextContent());
				list = doc.getElementsByTagName("status");
				toStore.getReponseMeteo().getMeteo().setStatus(list.item(0).getTextContent());
				
				associate.addMessageToStorage(toStore.getRequeteMeteo().getClient(), toStore);
				
				LOG.info("Message received : " + toStore.getRequeteMeteo().getClient() + " / "
				        + msgText);
				
			}
		} catch (JMSException jmse) {
			LOG.error("JMS error : message not received properly");
			jmse.printStackTrace();
		} catch (SAXException e) {
			LOG.error("Parsing error : message not well formed");
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			LOG.error("Parsing error : configuration not well setted");
			e.printStackTrace();
		} catch (IOException e) {
			LOG.error("I/O error : message not received properly");
			e.printStackTrace();
		}
	}
	
	protected static Document stringToDom(String xmlSource) throws SAXException,
	        ParserConfigurationException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		return builder.parse(new ByteArrayInputStream(xmlSource.getBytes("UTF-8")));
	}
	
	protected static String domToString(final Document _document) throws TransformerException {
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		DOMSource source = new DOMSource(_document);
		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		transformer.transform(source, result);
		return sw.toString();
	}
}
